<?php
/**
 * Created by PhpStorm.
 * User: xuyiping
 * Date: 2017/12/1
 * Time: 13:36
 */

namespace App\Http\Middleware;

use App\Model\User\PermissionModel;
use App\Model\User\RolePermissionModel;
use App\Model\User\UserRoleModel;
use Closure;
use Illuminate\Http\Request;

class AdminService
{

    public function handle(Request $request, Closure $next){

        //判断用户是否登录
        $user_id = session('ADMIN_USER_ID'.session()->getId());

        if( ! $user_id ){
            return redirect('/admin/login?redirect_url=' . urlencode($request->url()));
        }
        //查看用户的权限
        $str = strlen('http://'.$_SERVER['HTTP_HOST']);
        $url = substr($request->url(),$str+1);

        if( !strpos($url,'dashboard')  ){
            //根据URL查找权限号
            $permission = PermissionModel::select('permissionID')->where('permissionRequest',$url)->first();
            if($permission){
                $permissionID = $permission['permissionID'];
                //查询用户角色信息
                $role = UserRoleModel::select('roleID')->find($user_id);

                //查询用户角色权限组信息
                $role_permission_group = RolePermissionModel::where('roleID', $role->roleID)->get();

                if ($role_permission_group) {
                    $role_permission_group = $role_permission_group->pluck('permissionID')->toArray();
                } else {
                    $role_permission_group = [];
                }

                if(!in_array($permissionID,$role_permission_group)){
                    return redirect('/admin/permission/out');
                }
            }
        }

        return $next($request);
    }

}